<template>
  <div class="variable-rich-text-editor-container">
    <div 
      class="variable-rich-text-editor" 
      :class="{ 'multiline': multiline }"
      contenteditable="true"
      @input="onInput"
      @keydown="onKeydown"
      @paste="onPaste"
      ref="editor"
      :placeholder="placeholder"
    ></div>
    <div class="variable-dropdown" v-if="showVariableDropdown" :style="dropdownStyle">
      <div 
        v-for="(variable, index) in displayVariables" 
        :key="`${variable.sourceNodeId}-${variable.name}`"
        class="variable-option"
        :class="{ 'selected': index === selectedIndex }"
        @click="selectVariable(variable)"
        @mouseenter="selectedIndex = index"
      >
        {{ variable.sourceNode }} - {{ variable.name }}{{ variable.type ? `(${variable.type})` : '' }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'VariableRichTextEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入内容...'
    },
    availableVariables: {
      type: Array,
      default: () => []
    },
    inputVariables: {
      type: Array,
      default: () => []
    },
    multiline: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showVariableDropdown: false,
      dropdownPosition: { x: 0, y: 0 },
      triggerPosition: null,
      selectedIndex: -1 // 当前选中的变量索引
    }
  },
  computed: {
    dropdownStyle() {
      return {
        left: `${this.dropdownPosition.x}px`,
        top: `${this.dropdownPosition.y}px`
      }
    },
    
    displayVariables() {
      // 优先显示已选择的输入变量，如果没有则显示所有可用变量
      if (this.inputVariables && this.inputVariables.length > 0) {
        return this.inputVariables.map(inputVar => ({
          name: inputVar.outputName,
          type: inputVar.type || 'string',
          value: '',
          sourceNode: inputVar.nodeName,
          sourceNodeId: inputVar.nodeId
        }))
      }
      return this.availableVariables
    }
  },
  mounted() {
    // 初始化编辑器内容
    this.$nextTick(() => {
      if (this.$refs.editor) {
        this.$refs.editor.innerHTML = this.value || ''
      }
    })
  },
  watch: {
    value(newVal) {
      if (this.$refs.editor && this.$refs.editor.innerHTML !== newVal) {
        this.$refs.editor.innerHTML = newVal || ''
      }
    }
  },
  methods: {
    onInput(event) {
      const content = event.target.innerHTML
      this.updateContent(content)
    },
    
    onKeydown(event) {
      if (event.key === '/') {
        // 如果下拉框已经显示，先隐藏它并阻止输入
        if (this.showVariableDropdown) {
          event.preventDefault()
          this.hideDropdown()
          return
        }
        
        // 检查当前光标是否在变量标签内部，如果是则移动到标签后面
        this.moveCursorOutOfVariableTag()
        
        // 等待光标位置更新后再记录触发位置
        this.$nextTick(() => {
          // 再次检查并移动光标，确保光标在正确位置
          this.moveCursorOutOfVariableTag()
          
          // 等待光标移动完成后再记录触发位置
          this.$nextTick(() => {
            this.triggerPosition = this.getCursorPosition()
            this.showVariableDropdown = true
            this.selectedIndex = -1 // 重置选中索引
            
            // 延迟更新位置，确保DOM已更新
            this.$nextTick(() => {
              this.updateDropdownPosition(event)
            })
            
            // 再次延迟更新位置，确保所有DOM更新完成
            setTimeout(() => {
              this.updateDropdownPosition(event)
            }, 10)
          })
        })
        
        return
      } else if (event.key === 'Escape') {
        this.hideDropdown()
      } else if (this.showVariableDropdown) {
        // 处理键盘导航
        if (event.key === 'ArrowDown') {
          event.preventDefault()
          this.navigateDown()
        } else if (event.key === 'ArrowUp') {
          event.preventDefault()
          this.navigateUp()
        } else if (event.key === 'Enter') {
          event.preventDefault()
          this.selectCurrentVariable()
        } else {
          // 如果下拉框显示时输入其他字符，取消变量选择
          this.hideDropdown()
        }
      }
    },
    
    onPaste(event) {
      event.preventDefault()
      const text = event.clipboardData.getData('text/plain')
      document.execCommand('insertText', false, text)
    },
    
    updateContent(content) {
      // 对于多行编辑器，始终传递HTML内容以保持格式
      if (this.multiline) {
        this.$emit('input', content)
        this.$emit('change', content)
      } else {
        // 检查是否包含变量标签
        if (content.includes('variable-tag')) {
          // 如果包含变量标签，直接传递HTML内容
          this.$emit('input', content)
          this.$emit('change', content)
        } else {
          // 单行编辑器转换为纯文本
          const tempDiv = document.createElement('div')
          tempDiv.innerHTML = content
          const text = tempDiv.textContent || tempDiv.innerText || ''
          this.$emit('input', text)
          this.$emit('change', text)
        }
      }
    },
    
    updateDropdownPosition(event) {
      const rect = event.target.getBoundingClientRect()
      const selection = window.getSelection()
      
      if (selection.rangeCount > 0) {
        const range = selection.getRangeAt(0)
        const rect2 = range.getBoundingClientRect()
        
        // 使用fixed定位，计算相对于视口的位置
        const x = rect2.left
        const y = rect2.bottom + 2
        
        this.dropdownPosition = { x, y }
      } else {
        // 如果没有选择范围，使用默认位置
        const x = rect.left
        const y = rect.bottom + 2
        
        this.dropdownPosition = { x, y }
      }
    },
    
    selectVariable(variable) {
      // 确保编辑器有焦点
      this.$refs.editor.focus()
      
      // 如果有记录的触发位置，先删除触发字符 '/'
      if (this.triggerPosition) {
        this.removeTriggerCharacter()
      }
      
      // 获取当前光标位置
      const selection = window.getSelection()
      if (selection.rangeCount > 0) {
        const range = selection.getRangeAt(0).cloneRange()
        
        // 创建变量标签
        const typeText = variable.type ? `(${variable.type})` : ''
        const variableTag = `<span class="variable-tag" data-variable="${variable.name}" data-source="${variable.sourceNode}" contenteditable="false">${variable.sourceNode} - ${variable.name}${typeText}</span>`
        
        // 创建临时元素来解析HTML
        const tempDiv = document.createElement('div')
        tempDiv.innerHTML = variableTag
        const variableElement = tempDiv.firstChild
        
        // 插入变量标签
        range.insertNode(variableElement)
        
        // 移动光标到变量标签后面
        range.setStartAfter(variableElement)
        range.setEndAfter(variableElement)
        range.collapse(true)
        
        // 清除选择并设置新的选择
        selection.removeAllRanges()
        selection.addRange(range)
      }
      
      this.hideDropdown()
      
      // 延迟更新内容，确保DOM更新完成
      this.$nextTick(() => {
        const content = this.$refs.editor.innerHTML
        this.updateContent(content)
      })
    },
    
    // 隐藏下拉框
    hideDropdown() {
      this.showVariableDropdown = false
      this.triggerPosition = null
      this.selectedIndex = -1
    },
    
    // 向下导航
    navigateDown() {
      if (this.displayVariables.length === 0) return
      
      this.selectedIndex = Math.min(this.selectedIndex + 1, this.displayVariables.length - 1)
    },
    
    // 向上导航
    navigateUp() {
      if (this.displayVariables.length === 0) return
      
      this.selectedIndex = Math.max(this.selectedIndex - 1, 0)
    },
    
    // 选择当前高亮的变量
    selectCurrentVariable() {
      if (this.selectedIndex >= 0 && this.selectedIndex < this.displayVariables.length) {
        const variable = this.displayVariables[this.selectedIndex]
        this.selectVariable(variable)
      }
    },
    
    // 获取光标位置
    getCursorPosition() {
      const selection = window.getSelection()
      if (selection.rangeCount > 0) {
        const range = selection.getRangeAt(0)
        return {
          node: range.startContainer,
          offset: range.startOffset
        }
      }
      return null
    },
    
    // 根据位置找到文本节点
    findTextNodeAtPosition(position) {
      if (!position || !position.node) return null
      
      // 如果位置节点是文本节点，直接返回
      if (position.node.nodeType === Node.TEXT_NODE) {
        return position.node
      }
      
      // 否则在编辑器内查找文本节点
      const walker = document.createTreeWalker(
        this.$refs.editor,
        NodeFilter.SHOW_TEXT,
        null,
        false
      )
      
      let textNode
      let currentOffset = 0
      
      while (textNode = walker.nextNode()) {
        const nodeLength = textNode.length
        if (currentOffset <= position.offset && position.offset <= currentOffset + nodeLength) {
          return textNode
        }
        currentOffset += nodeLength
      }
      
      return null
    },
    

    

    
    // 删除触发字符 '/'
    removeTriggerCharacter() {
      if (!this.triggerPosition) return
      
      const textNode = this.findTextNodeAtPosition(this.triggerPosition)
      if (textNode) {
        const textContent = textNode.textContent || ''
        const offset = this.triggerPosition.offset
        
        if (offset < textContent.length && textContent[offset] === '/') {
          const range = document.createRange()
          range.setStart(textNode, offset)
          range.setEnd(textNode, offset + 1)
          range.deleteContents()
        } else {
          this.removeAllSlashCharacters()
        }
      } else {
        this.removeAllSlashCharacters()
      }
    },
    
    // 删除所有 / 字符
    removeAllSlashCharacters() {
      if (!this.$refs.editor) return
      
      const walker = document.createTreeWalker(
        this.$refs.editor,
        NodeFilter.SHOW_TEXT,
        null,
        false
      )
      
      let textNode
      while (textNode = walker.nextNode()) {
        const textContent = textNode.textContent || ''
        if (textContent.includes('/')) {
          // 找到包含 / 的文本节点，删除所有 / 字符
          const newText = textContent.replace(/\//g, '')
          textNode.textContent = newText
        }
      }
    },
    
    // 将光标移出变量标签
    moveCursorOutOfVariableTag() {
      const selection = window.getSelection()
      if (selection.rangeCount > 0) {
        const range = selection.getRangeAt(0)
        const container = range.commonAncestorContainer
        
        // 检查容器或其父元素是否是变量标签
        let variableTag = null
        
        if (container.nodeType === Node.TEXT_NODE && container.parentElement && container.parentElement.classList.contains('variable-tag')) {
          variableTag = container.parentElement
        } else if (container.nodeType === Node.ELEMENT_NODE && container.classList && container.classList.contains('variable-tag')) {
          variableTag = container
        } else {
          // 检查容器的父元素链中是否有变量标签
          let parent = container.parentElement
          while (parent && parent !== this.$refs.editor) {
            if (parent.classList && parent.classList.contains('variable-tag')) {
              variableTag = parent
              break
            }
            parent = parent.parentElement
          }
        }
        
        // 如果容器内容包含变量标签的文本，也认为光标在变量标签内部
        if (!variableTag && container.textContent && container.textContent.includes('开始 - ')) {
          // 查找最后一个变量标签
          const variableTags = this.$refs.editor.querySelectorAll('.variable-tag')
          if (variableTags.length > 0) {
            variableTag = variableTags[variableTags.length - 1]
          }
        }
        
        if (variableTag) {
          const newRange = document.createRange()
          newRange.setStartAfter(variableTag)
          newRange.setEndAfter(variableTag)
          newRange.collapse(true)
          selection.removeAllRanges()
          selection.addRange(newRange)
        }
      }
    }
  }
}
</script>

<style scoped>
.variable-rich-text-editor-container {
  position: relative;
}

.variable-rich-text-editor {
  min-height: 32px;
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: #fff;
  font-size: 12px;
  line-height: 1.5;
  outline: none;
  transition: border-color 0.3s;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.variable-rich-text-editor.multiline {
  min-height: 80px;
  max-height: 200px;
  overflow-y: auto;
  resize: vertical;
}

.variable-rich-text-editor:focus {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.variable-rich-text-editor:empty:before {
  content: attr(placeholder);
  color: #bfbfbf;
  pointer-events: none;
}

/* 变量标签样式 */
.variable-tag {
  display: inline-flex !important;
  align-items: center !important;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%) !important;
  color: #fff !important;
  padding: 2px 6px !important;
  border-radius: 12px !important;
  font-size: 10px !important;
  font-weight: 500 !important;
  margin: 0 2px !important;
  cursor: default !important;
  white-space: nowrap !important;
  max-width: 180px !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  box-shadow: 0 1px 3px rgba(24, 144, 255, 0.3) !important;
  position: relative !important;
  user-select: none !important;
}

.variable-tag::before {
  content: '' !important;
  display: inline-block !important;
  width: 4px !important;
  height: 4px !important;
  background: #fff !important;
  border-radius: 50% !important;
  margin-right: 4px !important;
  opacity: 0.8 !important;
}

.variable-tag:hover {
  background: linear-gradient(135deg, #40a9ff 0%, #69c0ff 100%) !important;
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.4) !important;
  transform: translateY(-1px) !important;
  transition: all 0.2s ease !important;
}

/* 全局样式，确保动态插入的元素也有样式 */
:global(.variable-tag) {
  display: inline-flex !important;
  align-items: center !important;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%) !important;
  color: #fff !important;
  padding: 2px 6px !important;
  border-radius: 12px !important;
  font-size: 10px !important;
  font-weight: 500 !important;
  margin: 0 2px !important;
  cursor: default !important;
  white-space: nowrap !important;
  max-width: 180px !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  box-shadow: 0 1px 3px rgba(24, 144, 255, 0.3) !important;
  position: relative !important;
  user-select: none !important;
}

:global(.variable-tag::before) {
  content: '' !important;
  display: inline-block !important;
  width: 4px !important;
  height: 4px !important;
  background: #fff !important;
  border-radius: 50% !important;
  margin-right: 4px !important;
  opacity: 0.8 !important;
}

:global(.variable-tag:hover) {
  background: linear-gradient(135deg, #40a9ff 0%, #69c0ff 100%) !important;
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.4) !important;
  transform: translateY(-1px) !important;
  transition: all 0.2s ease !important;
}

/* 变量下拉框样式 */
.variable-dropdown {
  position: fixed;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 10005;
  max-height: 200px;
  overflow-y: auto;
  min-width: 120px;
  margin-top: 0px;
}

.variable-option {
  padding: 6px 12px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
}

.variable-option:hover {
  background: #f5f5f5;
}

.variable-option.selected {
  background: #e6f7ff;
  color: #1890ff;
  border-left: 3px solid #1890ff;
}
</style> 